package com.easyOrder.core.identity;

import com.easyOrder.core.cache.CacheKeyPrefix;
import com.easyOrder.core.utils.Cryptos;
import com.easyOrder.core.utils.WebUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;

/**
 * Token生成器
 */
public class IdentityTokenProcessor {

    private static class SingleTonHolder {
        private static IdentityTokenProcessor instance = new IdentityTokenProcessor();
    }

    public static IdentityTokenProcessor getInstance() {
        return SingleTonHolder.instance;
    }

    public static final String AES_KEY = "meallink24518888";

    protected IdentityTokenProcessor() {
        super();
    }

    public static String getCacheKey(String sessionId) {
        return CacheKeyPrefix.Identity.getKey() + sessionId;
    }

    public static String getDeviceCacheKey(String sessionId, String deviceId) {
        return CacheKeyPrefix.Identity.getKey() + "_" + sessionId + "_" + deviceId;
    }

    public String generateToken(HttpServletRequest request) {
        try {
            Calendar ca = Calendar.getInstance();
            ca.add(Calendar.SECOND, (int) CacheKeyPrefix.Identity.getTimeout());
            StringBuilder bu = new StringBuilder();
            bu.append(WebUtils.Session.get().getId()).append("_")
                    .append(ca.getTime().getTime())
                    .append("_").append(WebUtils.Http.getIpAddr(request));
            return bytesToHexString((Cryptos.aesEncrypt(bu.toString().getBytes(), AES_KEY.getBytes())));
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public String generateDeviceToken(HttpServletRequest request) {
        try {
            Calendar ca = Calendar.getInstance();
            ca.add(Calendar.SECOND, (int) CacheKeyPrefix.Identity.getTimeout());
            StringBuilder bu = new StringBuilder();
            bu.append(WebUtils.Session.get().getId()).append("_")
                    .append(ca.getTime().getTime())
                    .append("_").append(WebUtils.Http.getIpAddr(request))
                    .append("_").append(WebUtils.Session.getDeviceId(request));
            return bytesToHexString((Cryptos.aesEncrypt(bu.toString().getBytes(), AES_KEY.getBytes())));
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }


    public static byte[] hexStringToByte(String hex) {
        int len = (hex.length() / 2);
        byte[] result = new byte[len];
        char[] achar = hex.toCharArray();
        for (int i = 0; i < len; i++) {
            int pos = i * 2;
            result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
        }
        return result;
    }

    private static byte toByte(char c) {
        byte b = (byte) "0123456789ABCDEF".indexOf(c);
        return b;
    }

    /** */
    /**
     * 把字节数组转换成16进制字符串
     *
     * @param bArray
     * @return
     */
    public static final String bytesToHexString(byte[] bArray) {
        StringBuffer builder = new StringBuffer(bArray.length);
        String sTemp;
        for (int i = 0; i < bArray.length; i++) {
            sTemp = Integer.toHexString(0xFF & bArray[i]);
            if (sTemp.length() < 2)
                builder.append(0);
            builder.append(sTemp.toUpperCase());
        }
        return builder.toString();
    }
}
